﻿using System;
using System.Web.Security;
using Dost.Khcn.Biz;
using Dost.Khcn.Model;
using Dost.Khcn.Web.Common;
using Resources;

namespace Dost.Khcn.Web
{
    public partial class Logon : System.Web.UI.Page
    {
        private EmployeeBiz _employeeBiz;
        private EmployeeBiz EmployeeManager
        {
            get { return _employeeBiz ?? (_employeeBiz = new EmployeeBiz()); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void BtnLogonClick(object sender, EventArgs e)
        {
            if (ValidateUser(txtUserName.Text, txtPassword.Text))
            {
                FormsAuthentication.SetAuthCookie(txtUserName.Text, chkPersistCookie.Checked);
                if (WebCommon.CurrrentEmployee.Role == UserRole.Admin)
                {
                    Response.Redirect("~/Admin/Default.aspx");
                }
                else
                {
                    Response.Redirect("~/Default.aspx");                    
                }
            }
            else
            {
                lblErrorMessage.Text = GlobalStrings.LoginFailed;
            }
        }

        private bool ValidateUser(string userName, string password)
        {
            var passwordHash = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
            var employee = EmployeeManager.Logon(userName, passwordHash);
            if (employee != null)
            {
                WebCommon.CurrrentEmployee = employee;
            }

            return employee != null;
        }
    }
}